package com.xjcs.saplingplan.dialog

import android.content.Context
import android.graphics.Color
import android.view.View
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.TimeUtils
import com.contrarywind.listener.OnItemSelectedListener
import com.contrarywind.view.WheelView
import com.lxj.xpopup.core.BottomPopupView
import com.nlf.calendar.Lunar
import com.nlf.calendar.LunarYear
import com.nlf.calendar.Solar
import com.xjcs.saplingplan.R
import com.xjcs.saplingplan.adapter.ArrayWheelAdapter
import com.xjcs.saplingplan.const.DateConst
import com.xjcs.saplingplan.const.addZero
import com.xjcs.saplingplan.const.dpToPx
import com.xjcs.saplingplan.const.setSingleClick
import com.xjcs.saplingplan.const.toColor
import com.xjcs.saplingplan.const.toStr
import com.xjcs.saplingplan.databinding.PopCountdownDateBinding
import java.time.LocalDate
import java.util.Calendar
import kotlin.math.max
import kotlin.math.min

class CountdownDatePop(
    context: Context,
    private var isLunar: Boolean,
    private var selectDateStr: String = LocalDate.now().toStr(),
    private val isBirthday: Boolean = false,
    private var hiddenYear: Boolean = false,
    private val callback: (hiddenYear: Boolean, isLunar: Boolean, memoTimeStr: String) -> Unit
) : BottomPopupView(context) {

    private val dp14 = 14.dpToPx(context).toFloat()

    private var pvTimeHasYear: TimePickerView? = null
    private var pvTimeSolarNoYear: TimePickerView? = null

    private val monthArray = mutableListOf("正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月")
    private val dayArray = mutableListOf(
        "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
        "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "廿十",
        "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十",)

    private lateinit var binding: PopCountdownDateBinding

    override fun getImplLayoutId(): Int {
        return R.layout.pop_countdown_date
    }

    override fun onCreate() {
        super.onCreate()
        binding = PopCountdownDateBinding.bind(bottomPopupContainer.getChildAt(0))
        if (isLunar) {
            refreshLunarUi()
        } else {
            refreshSolarUi()
        }
        if(hiddenYear){
            if(isLunar){
                convertSolarToLunar()
                initWheelViewLunarNoYear()
            }else{
                initWheelViewSolarNoYear()
            }
        }else{
            initWheelView()
        }
        initListener()
        binding.groupYear.visibility = if(isBirthday) VISIBLE else GONE
        binding.ivYearSwitch.setImageResource(if(hiddenYear) R.drawable.icon_switch_on else R.drawable.icon_switch_off)
    }

    /**
     * 有年份的滚轮
     */
    private fun initWheelView() {
        val curDate = LocalDate.parse(selectDateStr, DateConst.ymdFormat)
        val curCalendar = Calendar.getInstance()
        curCalendar.set(curDate.year, curDate.monthValue - 1, curDate.dayOfMonth)
        val startCalendar = Calendar.getInstance()
        startCalendar.set(1900, 0, 1)
        val endCalendar = Calendar.getInstance()
        endCalendar.set(2050, 11, 31)
        pvTimeHasYear = TimePickerBuilder(context) { date, v ->
            val dateFormat = TimeUtils.millis2String(date.time, "yyyy-MM-dd")
            callback.invoke(false, isLunar, dateFormat)
        }.setDate(curCalendar)
            .setTimeSelectChangeListener {
                selectDateStr = TimeUtils.millis2String(it.time, "yyyy-MM-dd")
            }
            .setRangDate(startCalendar, endCalendar)
            .setLayoutRes(R.layout.wheelview_select_date) {
            }
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setLabel("年", "月", "日", "", "", "")
            .setContentTextSize(23)
            .setSubCalSize(18)
            .setItemVisibleCount(3)
            .setLineSpacingMultiplier(2.5f)
            .isCyclic(false)
            .isAlphaGradient(true)
            .setTextColorCenter(Color.BLACK)
            .setTextColorOut("#B3000000".toColor())
            .setDecorView(binding.frameLayout)
            .setOutSideColor(0xFFFFFF)
            .setOutSideCancelable(false)
            .setDividerColor(Color.TRANSPARENT)
            .setLunarCalendar(isLunar)
            .build()

        pvTimeHasYear?.show(binding.frameLayout, false)
    }

    /**
     * 无年份的阳历滚轮
     */
    private fun initWheelViewSolarNoYear() {
        val curDate = LocalDate.parse(selectDateStr, DateConst.ymdFormat)
        val curCalendar = Calendar.getInstance()
        curCalendar.set(curDate.year, curDate.monthValue - 1, curDate.dayOfMonth)
        val startCalendar = Calendar.getInstance()
        startCalendar.set(1900, 0, 1)
        val endCalendar = Calendar.getInstance()
        endCalendar.set(2050, 11, 31)
        pvTimeSolarNoYear = TimePickerBuilder(context) { date, _ ->
            val dateFormat = selectDateStr.substring(0, 5) + TimeUtils.millis2String(date.time, "MM-dd")
            callback.invoke(true, false, dateFormat)
        }.setDate(curCalendar)
            .setTimeSelectChangeListener {
                selectDateStr = selectDateStr.substring(0, 5) + TimeUtils.millis2String(it.time, "MM-dd")
            }
            .setRangDate(startCalendar, endCalendar)
            .setLayoutRes(R.layout.wheelview_select_date) {
            }
            .setType(booleanArrayOf(false, true, true, false, false, false))
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setLabel("", "月", "日", "", "", "")
            .setContentTextSize(23)
            .setSubCalSize(18)
            .setItemVisibleCount(3)
            .setLineSpacingMultiplier(2.5f)
            .isCyclic(false)
            .isAlphaGradient(true)
            .setTextColorCenter(Color.BLACK)
            .setTextColorOut("#B3000000".toColor())
            .setDecorView(binding.frameLayout)
            .setOutSideColor(0xFFFFFF)
            .setOutSideCancelable(false)
            .setDividerColor(Color.TRANSPARENT)
            .setLunarCalendar(isLunar)
            .build()

        pvTimeSolarNoYear?.show(binding.frameLayout, false)
    }

    /**
     * 无年份的农历滚轮
     */
    private fun initWheelViewLunarNoYear() {
        val view = View.inflate(context, R.layout.wheelview_month_day, null)
        val monthView = view.findViewById<WheelView>(R.id.month)
        val dayView = view.findViewById<WheelView>(R.id.day)

        val split = selectDateStr.split("-")
        val month = split[1].toInt()
        val day = split[2].toInt()
        if(day > 30){
            selectDateStr = selectDateStr.substring(0, 5) + "${month.addZero()}-${30}"
        }
        initOnlyWheelView(monthView, {
            selectDateStr = selectDateStr.substring(0, 5) + "${(it + 1).addZero()}-${(dayView.currentItem + 1).addZero()}"
        }, monthArray, max(0, month - 1))
        initOnlyWheelView(dayView, {
            selectDateStr = selectDateStr.substring(0, 5) + "${(monthView.currentItem + 1).addZero()}-${(it + 1).addZero()}"
        }, dayArray, min(30, max(0, day - 1)))
        binding.frameLayout.addView(view)
    }

    private fun initOnlyWheelView(
        wheelView: WheelView,
        itemSelected: OnItemSelectedListener,
        list: MutableList<String>,
        currentItem: Int
    ){
        wheelView.adapter = ArrayWheelAdapter(list)
        wheelView.setOnItemSelectedListener(itemSelected)
        wheelView.setCyclic(false)
        wheelView.setItemsVisibleCount(3)
        wheelView.setLineSpacingMultiplier(2.5f)
        wheelView.setTextColorOut("#B3000000".toColor())
        wheelView.setTextColorCenter(Color.BLACK)
        wheelView.setDividerWidth(0)
        wheelView.setDividerColor(Color.TRANSPARENT)
        wheelView.setAlphaGradient(true)
        wheelView.currentItem = currentItem
    }

    /**
     * 阴历转换成阳历
     */
    private fun convertLunarToSolar() {
        val split = selectDateStr.split("-")
        var year = split[0].toInt()
        val month = split[1].toInt()
        val day = split[2].toInt()
        kotlin@run{
            for(i in 0..100){
                val lunarMonth = LunarYear.fromYear(year - i).getMonth(month)
                if(lunarMonth.dayCount >= day){
                    year -= i
                    return@run
                }
            }
        }

        val curSolar = Lunar(
            year, month, day
        ).solar
        selectDateStr = "${curSolar.year}" +
                "-" + curSolar.month.addZero() +
                "-" + curSolar.day.addZero()
    }

    /**
     * 阳历转换成阴历
     */
    private fun convertSolarToLunar() {
        val selectDate = LocalDate.parse(selectDateStr)
        val curLunar = Solar(selectDate.year, selectDate.monthValue, selectDate.dayOfMonth)
        selectDateStr = "${curLunar.year}" +
                "-" + curLunar.month.addZero() +
                "-" + curLunar.day.addZero()
    }

    private fun initListener() {
        //阳历
        binding.tvSolar.setSingleClick {
            if(!isLunar) return@setSingleClick
            isLunar = false
            binding.frameLayout.removeAllViews()
            if(isBirthday){ //生日
                if(hiddenYear){
                    initWheelViewSolarNoYear()
                }else{
                    initWheelView()
                }
            }else{
                initWheelView()
            }
            refreshSolarUi()
        }
        //农历
        binding.tvLunar.setSingleClick {
            if(isLunar) return@setSingleClick
            isLunar = true
            binding.frameLayout.removeAllViews()
            if(isBirthday){
                if(hiddenYear){
                    //（无年份）
                    initWheelViewLunarNoYear()
                }else{
                    initWheelView()
                }
            }else{
                initWheelView()
            }

            refreshLunarUi()
        }
        //忽略年份
        binding.ivYearSwitch.setSingleClick {
            hiddenYear = !hiddenYear
            binding.ivYearSwitch.setImageResource(if(hiddenYear) R.drawable.icon_switch_on else R.drawable.icon_switch_off)
            binding.frameLayout.removeAllViews()
            if(hiddenYear){
                //不显示年份
                if(isLunar){
                    convertSolarToLunar()
                    //农历
                    initWheelViewLunarNoYear()
                }else{
                    initWheelViewSolarNoYear()
                }
            }else{
                if(isLunar){
                    convertLunarToSolar()
                }
                //显示年份
                initWheelView()
            }
        }
        //取消
        binding.tvCancel.setSingleClick {
            dismiss()
        }
        //确定
        binding.tvSure.setSingleClick {
            if(isBirthday){
                if(hiddenYear){
                    if(isLunar){
                        convertLunarToSolar()
                        callback.invoke(true, true, selectDateStr)
                    }else{
                        pvTimeSolarNoYear?.returnData()
                    }
                }else{
                    pvTimeHasYear?.returnData()
                }
            }else{
                pvTimeHasYear?.returnData()
            }
            dismiss()
        }
    }

    private fun refreshLunarUi() {
        binding.tvLunar.setCornerRadius(dp14)
        binding.tvLunar.setBgColor(Color.BLACK)
        binding.tvLunar.setTextColor(Color.WHITE)

        binding.tvSolar.setCornerRadius(dp14, 0f, dp14, 0f)
        binding.tvSolar.setBgColor(Color.TRANSPARENT)
        binding.tvSolar.setTextColor(Color.BLACK)
    }

    private fun refreshSolarUi() {
        binding.tvSolar.setCornerRadius(dp14)
        binding.tvSolar.setBgColor(Color.BLACK)
        binding.tvSolar.setTextColor(Color.WHITE)

        binding.tvLunar.setCornerRadius(0f, dp14, 0f, dp14)
        binding.tvLunar.setBgColor(Color.TRANSPARENT)
        binding.tvLunar.setTextColor(Color.BLACK)
    }

}